﻿using PrinterMonitorSvc.Ext;
using PrinterMonitorSvc.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace PrinterMonitorSvc.Common
{
    /// <summary>
    /// 网络帮助类
    /// </summary>
    public static class NetHelper
    {
        #region 监听Http请求
        /// <summary>
        /// 监听Http请求
        /// </summary>
        /// <param name="listenerUrls">监听的URL集合,如(http://127.0.0.1:6789/test)</param>
        /// <param name="action">执行的动作</param>
        /// <param name="cancelListener">取消监听器,IsCancel=true取消监听,默认不取消</param>
        /// <param name="contentType">响应编码类型,默认(application/json)</param>
        public static void StartHttpListener(IEnumerable<string> listenerUrls, Action<HttpListenerRequest, HttpListenerResponse> action, CancelListener cancelListener = null, ContentType contentType = ContentType.Json)
        {
            if (!HttpListener.IsSupported)
            {
                throw new Exception("The current operating system does not support network listening");
            }
            if (null == listenerUrls || listenerUrls.Count() <= 0)
            {
                throw new Exception("The collection of monitored urls cannot be empty");
            }
            using (var listener = new HttpListener())
            {
                //添加监听路径
                foreach (var url in listenerUrls)
                {
                    string path = url.EndsWith("/") ? url : url + "/";
                    listener.Prefixes.Add(path);
                }
                //设置匿名访问
                listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                //开始监听
                listener.Start();
                while (true)
                {
                    if (null != cancelListener && cancelListener.IsCancel)
                    {
                        break;
                    }
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;
                    HttpListenerResponse response = context.Response;
                    response.ContentType = $"{contentType.ValueOfDescription()};charset=utf-8";
                    action.Invoke(request, response);
                }
            }
        }
        #endregion

        #region Ip(获取Ip)
        /// <summary>
        /// 获取局域网IP
        /// </summary>
        public static List<string> GetLanIps()
        {
            List<string> result = new List<string>();
            foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                    result.Add(hostAddress.ToString());
            }
            return result;
        }

        #endregion
    }
}
